package com.sc.service.impl.csm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sc.config.JWTProperties;
import com.sc.context.BaseContext;
import com.sc.domain.User;
import com.sc.dto.UserLoginDTO;
import com.sc.exception.LoginException;
import com.sc.mapper.csm.UserMapper;
import com.sc.service.csm.IUserService;
import com.sc.utils.JWTUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final JWTProperties jwtProperties;

    @Override
    public String login(UserLoginDTO userLoginDTO) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userLoginDTO.getUsername());
        User user = getOne(wrapper);

        if (user == null || !user.getPassword().equals(userLoginDTO.getPassword())) {
            throw new LoginException("用户名或密码错误");
        }

        Long userId = user.getId();
        BaseContext.setCurrentId(userId);

        String token = JWTUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                userId
        );

        return token;
    }

//    @Override
//    public void delete(UserDTO userDTO) {
//        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        wrapper.eq("username", userDTO.getUsername());
//        User user = getOne(wrapper);
//
//        if (user == null) {
//            throw new UserNotExistException(ExceptionConstant.USER_NOT_EXIST);
//        }
//
//        if (!user.getPassword().equals(userDTO.getPassword())) {
//            throw new PasswordMistakeException(ExceptionConstant.PASSWORD_MISTAKE);
//        }
//
//        remove(wrapper);
//    }
}